#!/usr/bin/env python3
"""
图片上传服务器
用于处理管理后台的图片上传请求
"""

import os
import json
import cgi
import cgitb
import http.server
import socketserver
import mimetypes
from datetime import datetime
import urllib.parse
import shutil

# 上传目录配置
UPLOAD_DIR = "static/uploads"
if not os.path.exists(UPLOAD_DIR):
    os.makedirs(UPLOAD_DIR, exist_ok=True)

class ImageUploadHandler(http.server.SimpleHTTPRequestHandler):
    """处理图片上传和其他请求"""
    
    def do_POST(self):
        """处理POST请求"""
        if self.path == '/api/upload-image':
            self.handle_image_upload()
        elif self.path == '/api/delete-image':
            self.handle_delete_image()
        else:
            self.send_error(404)
    
    def do_GET(self):
        """处理GET请求"""
        if self.path == '/api/images':
            self.handle_get_images()
        else:
            # 其他请求交给父类处理
            super().do_GET()
    
    def handle_image_upload(self):
        """处理图片上传"""
        try:
            # 解析multipart/form-data
            content_type = self.headers['Content-Type']
            if not content_type or 'multipart/form-data' not in content_type:
                self.send_error(400, "只支持multipart/form-data格式")
                return
            
            # 获取boundary
            boundary = content_type.split('boundary=')[1].strip('"')
            
            # 读取请求体
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            
            # 解析multipart数据
            parts = post_data.split(f'--{boundary}'.encode())
            
            for part in parts:
                if b'filename=' in part and b'Content-Type:' in part:
                    # 提取文件名
                    filename_match = part.split(b'filename="')[1].split(b'"')[0]
                    filename = filename_match.decode('utf-8')
                    
                    # 提取文件数据
                    file_data_start = part.find(b'\r\n\r\n') + 4
                    file_data_end = part.rfind(b'\r\n')
                    file_data = part[file_data_start:file_data_end]
                    
                    # 生成安全的文件名
                    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
                    safe_filename = f"{timestamp}_{filename}"
                    safe_filename = safe_filename.replace(' ', '_').replace('..', '_')
                    
                    # 保存文件
                    file_path = os.path.join(UPLOAD_DIR, safe_filename)
                    
                    with open(file_path, 'wb') as f:
                        f.write(file_data)
                    
                    # 返回成功响应
                    response = {
                        'success': True,
                        'imageUrl': f'/uploads/{safe_filename}',
                        'message': '图片上传成功'
                    }
                    
                    self.send_response(200)
                    self.send_header('Content-Type', 'application/json')
                    self.send_header('Access-Control-Allow-Origin', '*')
                    self.end_headers()
                    self.wfile.write(json.dumps(response).encode())
                    return
            
            # 没有找到图片文件
            response = {
                'success': False,
                'message': '未找到图片文件'
            }
            self.send_response(400)
            self.send_header('Content-Type', 'application/json')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(json.dumps(response).encode())
            
        except Exception as e:
            print(f"上传处理错误: {e}")
            response = {
                'success': False,
                'message': f'服务器处理错误: {str(e)}'
            }
            self.send_response(500)
            self.send_header('Content-Type', 'application/json')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(json.dumps(response).encode())
    
    def handle_get_images(self):
        """获取图片列表"""
        try:
            images = []
            for filename in os.listdir(UPLOAD_DIR):
                if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.gif', '.webp')):
                    file_path = os.path.join(UPLOAD_DIR, filename)
                    file_stat = os.stat(file_path)
                    images.append({
                        'name': filename,
                        'url': f'/uploads/{filename}',
                        'size': file_stat.st_size,
                        'modified': datetime.fromtimestamp(file_stat.st_mtime).isoformat()
                    })
            
            # 按修改时间排序，最新的在前
            images.sort(key=lambda x: x['modified'], reverse=True)
            
            response = {
                'success': True,
                'images': images
            }
            
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(json.dumps(response).encode())
            
        except Exception as e:
            print(f"获取图片列表错误: {e}")
            response = {
                'success': False,
                'message': f'获取图片列表失败: {str(e)}'
            }
            self.send_response(500)
            self.send_header('Content-Type', 'application/json')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(json.dumps(response).encode())
    
    def handle_delete_image(self):
        """删除图片"""
        try:
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            data = json.loads(post_data.decode())
            
            image_url = data.get('imageUrl')
            if not image_url:
                self.send_error(400, "缺少图片URL")
                return
            
            # 从URL中提取文件名
            filename = os.path.basename(image_url)
            file_path = os.path.join(UPLOAD_DIR, filename)
            
            if os.path.exists(file_path):
                os.remove(file_path)
                response = {
                    'success': True,
                    'message': '图片删除成功'
                }
                self.send_response(200)
            else:
                response = {
                    'success': False,
                    'message': '图片文件不存在'
                }
                self.send_response(404)
            
            self.send_header('Content-Type', 'application/json')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(json.dumps(response).encode())
            
        except Exception as e:
            print(f"删除图片错误: {e}")
            response = {
                'success': False,
                'message': f'删除图片失败: {str(e)}'
            }
            self.send_response(500)
            self.send_header('Content-Type', 'application/json')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(json.dumps(response).encode())
    
    def end_headers(self):
        """添加CORS头"""
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        super().end_headers()

def main():
    """主函数"""
    PORT = 8080
    
    # 更改工作目录到magazine
    os.chdir('magazine')
    
    with socketserver.TCPServer(("", PORT), ImageUploadHandler) as httpd:
        print(f"图片上传服务器运行在端口 {PORT}")
        print(f"上传目录: {UPLOAD_DIR}")
        print(f"访问地址: http://localhost:{PORT}")
        print("按 Ctrl+C 停止服务器")
        
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\n服务器已停止")

if __name__ == "__main__":
    main()